package encrypt

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"

	"gitee.com/wdxtub/gocdt/file"
)

// RSAEncrypt RSA 加密
func RSAEncrypt(plainText []byte, pubKeyPath string) ([]byte, error) {
	//打开文件
	buf, err := file.ReadFileContent(pubKeyPath)
	if err != nil {
		return nil, err
	}
	//pem解码
	block, _ := pem.Decode(buf)
	//x509解码

	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	//类型断言
	publicKey := publicKeyInterface.(*rsa.PublicKey)

	//对明文进行加密
	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
	if err != nil {
		return nil, err
	}
	//返回密文
	return cipherText, nil
}

// RSADecrypt RSA 解密
func RSADecrypt(cipherText []byte, privKeyPath string) ([]byte, error) {
	//打开文件
	buf, err := file.ReadFileContent(privKeyPath)
	if err != nil {
		return nil, err
	}
	//pem解码
	block, _ := pem.Decode(buf)
	//X509解码
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	//对密文进行解密
	plainText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
	if err != nil {
		return nil, err
	}
	//返回明文
	return plainText, nil
}
